package com.kepler.social.web.sharding;

import com.kepler.social.core.sharding.DatasourceType;
import org.apache.shardingsphere.sharding.api.sharding.hint.HintShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.hint.HintShardingValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.HashSet;

/**
 * 目前没有使用到该算法，按测试看，主从架构需要使用，如存疑，可以将commit回滚到之前的版本自行测试验证
 */
public class DatasourceRoutingAlgorithm implements HintShardingAlgorithm<String> {
    private static final Logger LOGGER = LoggerFactory.getLogger(DatasourceRoutingAlgorithm.class);
    @Deprecated
    private static final String SOCIAL_DS = "social_ds";
    private static final String DICT_DS = "dict_ds";
    private static final String LOVE_DS = "love_ds";
    private static final String USER_DS = "user_ds";
    private static final String USER_SECURITY_DS = "user_security_ds";


    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, HintShardingValue<String> shardingValue) {
        Collection<String> result = new HashSet<>();
        for (String value : shardingValue.getValues()) {
            if (DatasourceType.DATASOURCE_SOCAIL.toString().equals(value)) {
                if (availableTargetNames.contains(SOCIAL_DS)) {
                    result.add(SOCIAL_DS);
                }
            } else if (DatasourceType.DATASOURCE_DICT.toString().equals(value)) {
                if (availableTargetNames.contains(DICT_DS)) {
                    result.add(DICT_DS);
                }
            } else if (DatasourceType.DATASOURCE_LOVE.toString().equals(value)) {
                if (availableTargetNames.contains(LOVE_DS)) {
                    result.add(LOVE_DS);
                }
            } else if (DatasourceType.DATASOURCE_USER.toString().equals(value)) {
                if (availableTargetNames.contains(USER_DS)) {
                    result.add(USER_DS);
                }
            } else if (DatasourceType.DATASOURCE_USER_SECURITY.toString().equals(value)) {
                if (availableTargetNames.contains(USER_SECURITY_DS)) {
                    result.add(USER_SECURITY_DS);
                }
            } else {
                LOGGER.error("can't find the data source {}", value);
            }
        }
        LOGGER.info("availableTargetNames:{},shardingValue:{},返回的数据源:{}",
                new Object[]{availableTargetNames, shardingValue, result});
        return result;
    }
}
